let app = getApp();
import Toast from '@vant/weapp/toast/toast';

Page({
  data: {
    addressList: [],
    tokenString: '',
    isSelectMode: false, // 是否是选择地址模式
  },

  onLoad(options) {
    // 新增判断是否来自结算页
    if (options.select === 'true') {
      this.setData({ fromCheckout: true });
      wx.setNavigationBarTitle({ title: '选择收货地址' });
    }

    // 获取token
    wx.getStorage({
      key: "_token",
      success: (res) => {
        this.setData({
          tokenString: res.data
        });
        this.loadAddressList();
      },
      fail: () => {
        wx.navigateTo({
          url: '../login/login',
        });
      }
    });
  },

  // 加载地址列表
  loadAddressList() {
    wx.showLoading({
      title: '加载中...',
    });

    wx.request({
      url: 'https://kf.webxyq.com/findAddress',
      method: 'GET',
      data: {
        appkey: app.globalData.appkey,
        tokenString: this.data.tokenString
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data && res.statusCode === 200) {
          this.setData({
            addressList: res.data.result || []
          });
        } else {
          Toast(res.data.msg || '获取地址列表失败');
        }
      },
      fail: () => {
        wx.hideLoading();
        Toast('网络错误，请重试');
      }
    });
  },

  // 新增地址
  onAddAddress() {
    wx.navigateTo({
      url: '/pages/address-edit/address-edit'
    });
  },

  // 编辑地址
  onEditAddress(e) {
    const aid = e.currentTarget.dataset.aid;
    wx.navigateTo({
      url: `/pages/address-edit/address-edit?aid=${aid}`
    });
  },

  // 选择地址
  onSelectAddress(e) {
    if (this.data.fromCheckout) {
      const index = e.currentTarget.dataset.index;
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];
      
      prevPage.setData({
        'selectedAddress': this.data.addressList[index]
      });
      wx.navigateBack();
    }
  },

  // 删除地址
  onDeleteAddress(e) {
    const aid = e.currentTarget.dataset.aid;
    
    wx.showModal({
      title: '提示',
      content: '确定要删除这个地址吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '删除中...',
          });
          
          wx.request({
            url: 'https://kf.webxyq.com/deleteAddress',
            method: 'POST',
            data: {
              appkey: app.globalData.appkey,
              tokenString: this.data.tokenString,
              aid: aid
            },
            header: {
              "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
            },
            success: (res) => {
              wx.hideLoading();
              if (res.data && res.statusCode === 200) {
                Toast.success('删除成功');
                this.loadAddressList(); // 重新加载地址列表
              } else {
                Toast.fail(res.data.msg || '删除失败');
              }
            },
            fail: () => {
              wx.hideLoading();
              Toast.fail('网络错误，请重试');
            }
          });
        }
      }
    });
  },

  onShow() {
    // 如果有token，重新加载地址列表
    if (this.data.tokenString) {
      this.loadAddressList();
    }
  }
});